<template>
  <div class="w-100 com-status">
    <slot :label="label" :options="options">
        <span class="label">
            {{label}}
        </span>
    </slot>

  </div>
</template>

<script>
export default {
    name: 'com-status',
    props: {
        // 获取枚举的函数   TODO 后期考虑缓存函数的值，目前尽量传如支持缓存的函数
        getOptions: {
            type: Function
        },
        code: [String, Number], // 编码值
        keyName: {
            type: String,
            default: 'value'
        },
        labelName: {
            type: String,
            default: "label"
        }
    },
    data() {
        return {
            options: []
        }
    },
    computed: {
        label() {
            let code = String(this.code);
            let isEmpty = ['null', 'undefined'].includes(code);
            let active = (this.options||[]).find(v => {
                return String(v[this.keyName]) === code;
            });

            return _.get(active, `${this.labelName}`) || (isEmpty ? '' : code);
        }
    },
    watch:{
        getOptions: {
            immediate: true,
            handler() {
                this.getStatic();
            }
        }
    },
    created() {

    },
    methods: {
        // 获取枚举
        async getStatic() {
            let result = [];
            if(typeof this.getOptions === 'function') {
                result = this.getOptions();
            }

            if(result?.then) {
                result.then(res => {
                    this.options = res;
                }).catch(e => {
                    this.options = [];
                })
            }else {
                this.options = result;
            }
        }
    }
}
</script>

<style>

</style>